package cn.rkylin.oms.salespromotion.rules.controller;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.goods.domain.GoodsSku;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.order.vo.OrderVO;
import cn.rkylin.oms.salespromotion.rules.dao.impl.mybatis.SalesPromotionRuleDAOImpl;
import cn.rkylin.oms.salespromotion.rules.service.ISalesPromotionRuleService;
import cn.rkylin.oms.salespromotion.rules.vo.SalesPromotionRuleVO;

/**
 * 促销规则控制器
 *
 * @author zhanghao
 * @version 1.0.0
 * @created 2017-8-17
 */
@Controller
@RequestMapping("/salesPromotion")
public class SalesPromotionRuleController extends ApolloController {
    private static final Log logger = LogFactory.getLog(SalesPromotionRuleController.class);
    /**
     * 促销规则服务层
     */
    @Autowired
    private ISalesPromotionRuleService ruleService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    public IOrderService orderService;

    public SalesPromotionRuleController() {

    }

    /**
     * 查询促销规则
     *
     * @param quickSearch
     * @param start
     * @param length
     * @param formJson
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/ruleList")
    public Map<String, Object> getRuleList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        SalesPromotionRuleVO queryParamVO = new SalesPromotionRuleVO();
        if (quickSearch != null) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setSearchCondition(quickSearch);
            }
        }

        formJson = URLDecoder.decode(formJson, "UTF-8");
        @SuppressWarnings("unchecked")
        Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
        if (mapItem != null) {
            if (StringUtils.isNotEmpty(mapItem.get("isEnable"))) {
                queryParamVO.setIsEnable(mapItem.get("isEnable"));
                ;
            }
            if (StringUtils.isNotEmpty(mapItem.get("isExpire"))) {
                queryParamVO.setIsExpire(mapItem.get("isExpire"));
            }

            if (StringUtils.isNotEmpty(mapItem.get("querySendType"))) {
                queryParamVO.setQuerySendType(mapItem.get("querySendType"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryShopId"))) {
                queryParamVO.setQueryShopId(mapItem.get("queryShopId"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryConstrainGoods"))) {
                queryParamVO.setQueryConstrainGoods(mapItem.get("queryConstrainGoods"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryGift"))) {
                queryParamVO.setQueryGift(mapItem.get("queryGift"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryDateType"))) {
                queryParamVO.setQueryDateType(mapItem.get("queryDateType"));
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
            }

            if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
            }

        }

        Map<String, String> replaceFieldsMap = new HashMap<String, String>();

        // 排序语句生成
        String orderStatement = getOrderString(SalesPromotionRuleDAOImpl.class.getName(), "pageSelectSalesPromotionRule", replaceFieldsMap);
        if (StringUtils.isNotEmpty(orderStatement)) {
            queryParamVO.setOrderBy(orderStatement);
        }

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }

        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        queryParamVO.setProjectId(projectId);

        // 处理分页信息
        if (length == -1) {
            length = Integer.MAX_VALUE;
        }
        int page = start / length + 1;

        // 执行查询
        PageInfo<SalesPromotionRuleVO> ruleVOList = ruleService.findRuleList(page, length, queryParamVO);
        Map<String, Object> returnMap = getSuccessMap("查询数据成功");
        returnMap.put(RECORDS_FILTERED, ruleVOList.getTotal());
        returnMap.put(RECORDS_TOTAL, ruleVOList.getTotal());
        returnMap.put(RETURN_DATA, ruleVOList.getList());
        return returnMap;
    }

    /**
     * 根据ID查询促销规则
     *
     * @param ruleId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/ruleObject")
    public Map<String, Object> getRuleById(String ruleId) throws Exception {
        SalesPromotionRuleVO salesPromotionRule = ruleService.findRuleById(ruleId);
        Map<String, Object> returnMap = getSuccessMap("完成根据ID查询规则数据");
        returnMap.put(RETURN_DATA, salesPromotionRule);
        return returnMap;
    }

    /**
     * 查询促销规则状态的数值
     *
     * @param
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/queryStateCount")
    public Map<String, Object> queryStateCount(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        SalesPromotionRuleVO queryParamVO = new SalesPromotionRuleVO();
        if (quickSearch != null) {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                queryParamVO.setSearchCondition(quickSearch);
            }
        }

        formJson = URLDecoder.decode(formJson, "UTF-8");
        @SuppressWarnings("unchecked")
        Map<String, String> mapItem = JSONObject.parseObject(formJson, Map.class);
        if (mapItem != null) {
            if (StringUtils.isNotEmpty(mapItem.get("isEnable"))) {
                queryParamVO.setIsEnable(mapItem.get("isEnable"));
                ;
            }
            if (StringUtils.isNotEmpty(mapItem.get("isExpire"))) {
                queryParamVO.setIsExpire(mapItem.get("isExpire"));
            }

            if (StringUtils.isNotEmpty(mapItem.get("querySendType"))) {
                queryParamVO.setQuerySendType(mapItem.get("querySendType"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryShopId"))) {
                queryParamVO.setQueryShopId(mapItem.get("queryShopId"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryConstrainGoods"))) {
                queryParamVO.setQueryConstrainGoods(mapItem.get("queryConstrainGoods"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryGift"))) {
                queryParamVO.setQueryGift(mapItem.get("queryGift"));
            }
            if (StringUtils.isNotEmpty(mapItem.get("queryDateType"))) {
                queryParamVO.setQueryDateType(mapItem.get("queryDateType"));
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            if (StringUtils.isNotEmpty(mapItem.get("queryDateStart"))) {
                queryParamVO.setQueryDateStart(sdf.parse(mapItem.get("queryDateStart")));
            }

            if (StringUtils.isNotEmpty(mapItem.get("queryDateEnd"))) {
                queryParamVO.setQueryDateEnd(sdf.parse(mapItem.get("queryDateEnd")));
            }

        }

        Map<String, String> replaceFieldsMap = new HashMap<String, String>();

        // 排序语句生成
        String orderStatement = getOrderString(SalesPromotionRuleDAOImpl.class.getName(), "pageSelectSalesPromotionRule", replaceFieldsMap);
        if (StringUtils.isNotEmpty(orderStatement)) {
            queryParamVO.setOrderBy(orderStatement);
        }

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            return getFailedMap("查询当前登录人失败");
        }

        String projectId = currentUser.getCurrentProject().getPrjId();
        if (StringUtils.isBlank(projectId)) {
            return getFailedMap("查询当前登录人所属项目失败");
        }
        queryParamVO.setProjectId(projectId);

        // 执行查询
        List<HashMap> stateMap = ruleService.findStateCount(queryParamVO);
        Map<String, Object> returnMap = getSuccessMap("完成根据ID查询规则数据");
        returnMap.put(RETURN_DATA, stateMap);
        return returnMap;
    }

    /**
     * 获取系统订单促销规格，返回待上赠品信息
     *
     * @param strOrderVO
     *            系统订单实体JSON，内部包含系统订单商品
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getRuleByOrderVO", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> getRuleByOrderVO(@RequestBody String strOrderVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 解析系统订单，作为调用促销规则入参
            OrderVO orderVO = JSON.parseObject(strOrderVO, OrderVO.class);
            if (orderVO.getOrderTime() == null || orderVO.getPaidDate() == null || StringUtils.isEmpty(orderVO.getShopId())
                    || orderVO.getPaidFee().compareTo(new BigDecimal(0)) < 1) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "订单信息不完整，不能计算赠品");
                return returnMap;
            }

            // 获取赠品列表，其中key为规则ID，value为赠品的map<skuId,count>
            Map<String, Object> giftList = ruleService.generateGiftList(orderVO);

            // 根据giftList构造赠品列表
            Iterator<String> ruleIterator = giftList.keySet().iterator(); // 规则赠品Map的迭代器
            Map<String, JSONObject> orderSkuMap = new HashMap<String, JSONObject>(); // 缓存赠品对象
            while (ruleIterator.hasNext()) {
                String ruleKey = ruleIterator.next();

                Object giftObj = giftList.get(ruleKey);
                if (giftObj instanceof String) {
                    continue; // 按照规则计算错误，直接跳过
                } else {
                    List<Map<String, Object>> presentArray = (List<Map<String, Object>>) giftList.get(ruleKey);

                    for (Map<String, Object> map : presentArray) {
                        String skuId = (String) map.get("skuId");
                        GoodsSku goodsSku = goodsService.getGoodsSkuBySkuId(skuId);
                        JSONObject tempObj = new JSONObject();
                        // OrderSkuVO value = new OrderSkuVO();
                        // value.setQty(sendCount);
                        tempObj.put("skuCode", goodsSku.getSkuCode());
                        tempObj.put("skuId", goodsSku.getSkuId());
                        tempObj.put("skuName", goodsSku.getSkuName());
                        tempObj.put("goodsId", goodsSku.getGoodsId());
                        tempObj.put("goodsCode", goodsSku.getGoodsCode());
                        tempObj.put("goodsName", goodsSku.getGoodsName());

                        tempObj.put("isVirt", goodsSku.getVirtYn());
                        tempObj.put("salePrice", goodsSku.getSalePrice());
                        tempObj.put("goodsSkuCost", goodsSku.getCostPrice());
                        int sendCount = (Integer) map.get("sendCount");
                        // 如果赠品的数量为数字，则相加，否则不相加
                        if (StringUtils.isNumeric(String.valueOf(sendCount))) {
                            if (null == orderSkuMap.get(skuId)) {
                                tempObj.put("sendCount", sendCount);
                                orderSkuMap.put(skuId, tempObj);
                            } else {
                                // 向Map中的赠品对象追加数量
                                int count = orderSkuMap.get(skuId).getIntValue("sendCount");
                                orderSkuMap.get(skuId).put("sendCount", count + sendCount);
                            }
                            logger.debug("按规则【" + ruleKey + "】计算赠品后，赠品【" + skuId + "】的赠送数量为：" + orderSkuMap.get(skuId).getIntValue("sendCount"));
                        }
                    }
                }
            }

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, orderSkuMap);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 获取系统订单促销规格，返回待上赠品信息
     *
     * @param strOrderVO
     *            系统订单实体JSON，内部包含系统订单商品
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getRuleByOrder", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public Map<String, Object> getRuleByOrder(String orderId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            OrderVO paramVO = new OrderVO();
            paramVO.setOrderId(orderId);
            // 解析系统订单，作为调用促销规则入参
            PageInfo<OrderVO> orderVOList = orderService.findByWhere(0, Integer.MAX_VALUE, paramVO);

            OrderVO orderVO = orderVOList.getList().get(0);

            if (orderVO.getOrderTime() == null || orderVO.getPaidDate() == null || StringUtils.isEmpty(orderVO.getShopId())
                    || orderVO.getPaidFee().compareTo(new BigDecimal(0)) < 1) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "订单信息不完整，不能计算赠品");
                return returnMap;
            }

            // 获取赠品列表，其中key为规则ID，value为赠品的map<skuId,count>
            Map<String, Object> giftList = ruleService.generateGiftList(orderVO);

            // 根据giftList构造赠品列表
            Iterator<String> ruleIterator = giftList.keySet().iterator(); // 规则赠品Map的迭代器
            Map<String, JSONObject> orderSkuMap = new HashMap<String, JSONObject>(); // 缓存赠品对象
            while (ruleIterator.hasNext()) {
                String ruleKey = ruleIterator.next();

                Object giftObj = giftList.get(ruleKey);
                if (giftObj instanceof String) {
                    continue; // 按照规则计算错误，直接跳过
                } else {
                    List<Map<String, Object>> presentArray = (List<Map<String, Object>>) giftList.get(ruleKey);

                    for (Map<String, Object> map : presentArray) {
                        String skuId = (String) map.get("skuId");
                        GoodsSku goodsSku = goodsService.getGoodsSkuBySkuId(skuId);
                        JSONObject tempObj = new JSONObject();
                        // OrderSkuVO value = new OrderSkuVO();
                        // value.setQty(sendCount);
                        tempObj.put("skuCode", goodsSku.getSkuCode());
                        tempObj.put("skuId", goodsSku.getSkuId());
                        tempObj.put("skuName", goodsSku.getSkuName());
                        tempObj.put("goodsId", goodsSku.getGoodsId());
                        tempObj.put("goodsCode", goodsSku.getGoodsCode());
                        tempObj.put("goodsName", goodsSku.getGoodsName());

                        tempObj.put("isVirt", goodsSku.getVirtYn());
                        tempObj.put("salePrice", goodsSku.getSalePrice());
                        tempObj.put("goodsSkuCost", goodsSku.getCostPrice());
                        int sendCount = (Integer) map.get("sendCount");
                        // 如果赠品的数量为数字，则相加，否则不相加
                        if (StringUtils.isNumeric(String.valueOf(sendCount))) {
                            if (null == orderSkuMap.get(skuId)) {
                                tempObj.put("sendCount", sendCount);
                                orderSkuMap.put(skuId, tempObj);
                            } else {
                                // 向Map中的赠品对象追加数量
                                int count = orderSkuMap.get(skuId).getIntValue("sendCount");
                                orderSkuMap.get(skuId).put("sendCount", count + sendCount);
                            }
                        }
                    }
                }
            }

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, orderSkuMap);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 创建促销规则
     *
     * @param ruleVO
     *            前台值映射到SalesPromotionRuleVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/addRule", method = RequestMethod.POST)
    @SystemControllerLog(module = "促销规则管理", operation = "创建促销规则")
    public Map<String, Object> addRule(@RequestBody SalesPromotionRuleVO ruleVO) throws Exception {
        // 如果即将启用，则校验时间
        if (YesNoConst.YES.equalsIgnoreCase(ruleVO.getIsEnable())) {
            Date now = new Date();
            if (ruleVO.getCountingDateStart().before(now)) {
                return getFailedMap("已过了规则开始时间，不能启用");
            }

        }

        ruleVO.setRuleId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        ruleVO.setCreateTime(new Date());

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        ruleVO.setCreator(currentUser.getAccount());
        ruleVO.setProjectId(currentUser.getCurrentProject().getPrjId());

        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            Map<String, Object> resultMap = getFailedMap("当前用户没有企业ID");
            return resultMap;
        }
        String entId = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
            if (StringUtils.isNotEmpty(entId)) {
                break;
            }
        }
        ruleVO.setEntId(entId);
        ruleVO.setUpdateTime(new Date());
        try {
            ruleService.insertRule(ruleVO);
            return getSuccessMap("新增促销规则成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
    }

    /**
     * 校验促销规则
     *
     * @param ruleVO
     *            前台值映射到SalesPromotionRuleVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/validDuplicateRule", method = RequestMethod.POST)
    public Map<String, Object> validDuplicateRule(@RequestBody SalesPromotionRuleVO ruleVO) throws Exception {
        ruleVO.setRuleId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        ruleVO.setCreateTime(new Date());

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        ruleVO.setCreator(currentUser.getAccount());
        ruleVO.setProjectId(currentUser.getCurrentProject().getPrjId());

        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            Map<String, Object> resultMap = getFailedMap("当前用户没有企业ID");
            return resultMap;
        }
        String entId = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
            if (StringUtils.isNotEmpty(entId)) {
                break;
            }
        }
        ruleVO.setEntId(entId);
        ruleVO.setUpdateTime(new Date());
        try {
            if (!ruleService.duplicatedValid(ruleVO)) {
                return getFailedMap("存在类型相同的促销规则，保存并启用将可能导致同一订单重复赠送，是否确认保存？");
            }
            return getSuccessMap("促销规则校验成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
    }

    /**
     * 更新促销规则
     *
     * @param ruleVO
     *            前台值映射到SalesPromotionRuleVO
     * @return 返回值JSON格式字符串
     */
    @ResponseBody
    @RequestMapping(value = "/updateRule", method = RequestMethod.POST)
    @SystemControllerLog(module = "促销规则管理", operation = "更新促销规则", keyCode = "ruleId")
    public Map<String, Object> updateRule(@RequestBody SalesPromotionRuleVO ruleVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 如果即将启用，则校验时间
            if (YesNoConst.YES.equalsIgnoreCase(ruleVO.getIsEnable())) {
                Date now = new Date();
                if (ruleVO.getCountingDateStart().before(now)) {
//                    returnMap.put(JSON_RESULT, FAILED);
//                    returnMap.put(JSON_MSG, "已过了规则开始时间，不能启用");
                     return getFailedMap("已过了规则开始时间，不能启用");
                }

            }

            ruleService.updateRule(ruleVO);
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "更新促销规则成功");
            // return getSuccessMap("更新促销规则成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
        returnMap.put("ruleId", ruleVO.getRuleId());
        return returnMap;
    }

    /**
     * 启用促销规则
     *
     * @param ruleId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/enableRule")
    @SystemControllerLog(module = "促销规则管理", operation = "启用促销规则", keyCode = "ruleId")
    public Map<String, Object> enableRule(String ruleId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            SalesPromotionRuleVO ruleObj = ruleService.findRuleById(ruleId);
            Date now = new Date();
            if (ruleObj.getCountingDateStart().before(now)) {
//                returnMap.put(JSON_RESULT, FAILED);
//                returnMap.put(JSON_MSG, "已过了规则开始时间，不能启用");
                return getFailedMap("已过了规则开始时间，不能启用");
            }

            ruleService.enableRuleState(ruleId);
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "已启用规则");
            // return getSuccessMap("已启用规则");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
        returnMap.put("ruleId", ruleId);
        return returnMap;
    }

    /**
     * 停用促销规则
     *
     * @param ruleId
     *            促销规则ID
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/disableRule")
    @SystemControllerLog(module = "促销规则管理", operation = "启用促销规则", keyCode = "ruleId")
    public Map<String, Object> disableRule(String ruleId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ruleService.disableRuleState(ruleId);
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "已停用规则");
            // return getSuccessMap("已停用规则");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
        returnMap.put("ruleId", ruleId);
        return returnMap;
    }

    /**
     * 删除促销规则
     *
     * @param ruleId
     *            促销规则ID
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/deleteRule")
    @SystemControllerLog(module = "促销规则管理", operation = "删除促销规则", keyCode = "ruleId")
    public Map<String, Object> deleteRule(String ruleId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ruleService.deleteRule(ruleId);
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "已删除规则");
            // return getSuccessMap("已删除规则");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
        returnMap.put("ruleId", ruleId);
        return returnMap;
    }

    /**
     * 复制促销规则
     *
     * @param ruleId
     *            促销规则ID
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/copyRule")
    @SystemControllerLog(module = "促销规则管理", operation = "复制促销规则", keyCode = "ruleId")
    public Map<String, Object> copyRule(String ruleId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            SalesPromotionRuleVO ruleVO = ruleService.insertRuleByOriginRuleId(ruleId);
            // Map<String, Object> returnMap = getSuccessMap("复制并打开新的促销规则");
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "复制并打开新的促销规则");
            returnMap.put(RECORDS_FILTERED, "1");
            returnMap.put(RECORDS_TOTAL, "1");
            returnMap.put(RETURN_DATA, ruleVO);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return getFailedMap(ex.getMessage());
        }
        returnMap.put("ruleId", ruleId);
        return returnMap;
    }

    private Map<String, Object> getSuccessMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, SUCCESS);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    }

    ;

    private Map<String, Object> getFailedMap(String message) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put(JSON_RESULT, FAILED);
        returnMap.put(JSON_MSG, message);
        return returnMap;
    }

    ;
}
